//
//  HelpDetailViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/8/10.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD

class HelpDetailViewController: BaseViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var webView: UIWebView!
  @IBOutlet private weak var titleLabel: UILabel!
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  private func loadHelpDetail() {
    func handleError() {
      HUD.flash(.labeledError(title: "帮助读取失败", subtitle: "请重试"), delay: 1.5)
      self.navigationController?.popViewController(animated: true)
    }
    
    if let helpID = helpTitle?.id {
      HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
      API.shared.requestAPI (
        APIURLStrings.getHelpDetails(helpID: helpID),
        method: .get,
        successCallback: { json in
          let helpJSON = json["help"]
          if let content = helpJSON["content"].string {
            HUD.hide()
            self.webView.loadHTMLString(content, baseURL: nil)
          } else {
            handleError()
          }
      }) { (message, code) in
        loggingPrint("Load help detail failed. \(message)")
        handleError()
      }
    }
  }
  
  // MARK: - Public vars
  
  var helpTitle: HelpTitle?
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    titleLabel.text = helpTitle?.title
    loadHelpDetail()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
}

extension HelpDetailViewController: UIWebViewDelegate {
  func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.injectDefaultStyle()
  }
  
  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
    if navigationType == .linkClicked {
      if let url = request.url {
        let alert = UIAlertController (
        title: "即将跳转到浏览器打开链接",
        message: "继续吗？",
        cancelTitle: "取消",
        cancelHandler: nil,
        confirmTitle: "继续") { _ in
          UIApplication.shared.open(url)
        }
        present(alert, animated: true)
      }
      return false
    } else {
      return true
    }
  }
}
